<?php
class DBO
{
    private $link;//公共方法
    public function __construct()
    {
        $this->link=$dbh= new PDO('mysql:host=127.0.0.1;dbname=1705phpa', 'root', 'root');//链接数据库
        $this->link->setAttribute(PDO::ATTR_ERRMODE,1);//报错信息
        $this->link->exec("set names utf8");//格式
    }
    //查询一条
    public function getOne($table,$where="1")
    {
        if(empty($table) || empty($where))
        {
            return "不能为空";
        }
        $sql="select * from $table WHERE $where";
        echo $sql;
        $res=$this->link->query($sql);
        return $res->fetch(2);
    }
    //查询多条
    public function getOnee($table,$where="1")
    {
        if(empty($table) || empty($where))
        {
            return "不能为空";
        }
        $sql="select * from $table WHERE $where";
        echo $sql;
        $res=$this->link->query($sql);
        return $res->fetchAll(2);
    }
    //添加
    public function add($table,$array)
    {
        if(empty($table) || count($array)==0)
        {
            return "不能为空";
        }
        $field="";
        $val="";
        foreach($array as $k=>$v)
        {
            $field.="`$k`,";
            $val.="'$v',";
        }
        $field=substr($field,0,-1);
        $val=substr($val,0,-1);

        $sql="insert into `$table` ($field) VALUE ($val)";
        return $this->link->exec($sql);
    }
    //删除
    public function del($table,$where)
    {
        if(empty($table) || empty($where))
        {
            return "不能为空";
        }
        $str="";
        foreach($where as $k=>$v)
        {
            $str="`$k`=$v";
        }

        $sql="delete from `$table` WHERE $str";
        return $this->link->exec($sql);
    }
    //修改
    public function updata($table,$where,$arr)
    {
        if(empty($table) || empty($where))
        {
            return "不能为空";
        }
        $str='';
        foreach($where as $k=>$v)
        {
            $str="`$k`='$v'";
        }
        $sql="update `$table` set $str WHERE $arr";
        echo  $sql;
        return $this->link->exec($sql);
    }

}


//查询一条
//$db=new DBO();
//$resd=$db->getOne("new");
//var_dump($resd);

//查询多条
//$db=new DBO();
//$resd=$db->getOnee("new");
//var_dump($resd);

//添加
//$db=new DBO();
//$array=['n_title'=>'腾讯','n_desc'=>'内幕'];
//$resd=$db->add("new",$array);
//var_dump($resd);

//删除
//$db=new DBO();
//$resd=$db->del('new',['n_id'=>1]);
//var_dump($resd);

//修改
//$db=new DBO();
//$resd=$db->updata('new',['n_desc'=>'百度'],'n_id=2');
//var_dump($resd);

?>


